<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/home/spumanage/spuaccount"
        >商品台账</el-breadcrumb-item
      >
      <el-breadcrumb-item>配置sku</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              <i class="el-icon-s-tools"></i> &nbsp; SKU管理
            </h3>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: right">
          <div class="grid-content bg-purple">
            <el-button
              size="small"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="showAddSkuDialog"
            >
              新增SKU
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="el-icon-refresh-left"
              @click="handleStockSynchronise"
            >
              同步SPU库存
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="el-icon-refresh-left"
              @click="handlePriceSynchronise"
            >
              同步SPU价格
            </el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-table
      border
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column align="center" label="编号" width="100">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="标题">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>
      <el-table-column align="center" label="售价" width="120">
        <template slot-scope="scope">{{ scope.row.price }}</template>
      </el-table-column>

      <!-- 动态加载SKU，显示操作列 -->
      <el-table-column
        align="center"
        :label="item.name"
        v-for="(item, i) in attrList"
        :key="i"
      >
        <template slot-scope="scope">{{
          scope.row.specifications[i].attributeValue
        }}</template>
      </el-table-column>

      <el-table-column align="center" label="库存" width="120">
        <template slot-scope="scope">{{ scope.row.stock }}</template>
      </el-table-column>
      <el-table-column align="center" label="库存预警值" width="120">
        <template slot-scope="scope">{{ scope.row.stockThreshold }}</template>
      </el-table-column>

      <el-table-column align="center" label="排序" width="80">
        <template slot-scope="scope">{{ scope.row.sort }}</template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="100">
        <template slot-scope="scope">
          <!-- <el-button
            title="编辑"
            type="warning"
            size="mini"
            icon="el-icon-edit"
            circle
            @click="$router.push('#' + scope.row.id)"
          ></el-button> -->
          <el-button
            title="删除"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            circle
            @click="$router.push('#' + scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
      >
      </el-pagination>
    </div>

    <!-- 新增SKU的弹窗 -->
    <el-dialog
      title="新增SKU"
      :visible.sync="addDialogVisible"
      :modal-append-to-body="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="130px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="16">
            <el-form-item label="SKU标题" prop="title">
              <el-input
                size="small"
                placeholder="请输入SKU标题"
                v-model="ruleForm.title"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 单选按钮属性模板 -->
        <el-row v-for="(item, i) in attrList" :key="i">
          <el-form-item
            v-if="item.inputType == 1"
            :label="item.name"
            :prop="item.name"
          >
            <el-radio-group v-model="selectedAttrList[item.name]">
              <el-radio
                v-for="(val, j) in item.valueList.split(',')"
                :key="j"
                :label="val"
              >
                {{ val }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 复选框属性模板 -->
          <el-form-item
            v-if="item.inputType == 2"
            :label="item.name"
            :prop="item.name"
          >
            <el-checkbox-group v-model="selectedAttrList[item.name]">
              <el-checkbox
                v-for="(opt, j) in item.valueList.split(',')"
                :key="j"
                :label="opt"
              >
                {{ opt }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="价格" prop="price">
              <el-input
                size="small"
                placeholder="请输入价格"
                v-model="ruleForm.price"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="当前库存" prop="stock">
              <el-input placeholder="请输入当前库存" v-model="ruleForm.stock">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="库存预警阈值" prop="stockThreshold">
              <el-input
                placeholder="请输入库存预警阈值"
                v-model="ruleForm.stockThreshold"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16">
            <el-form-item label="排序序号" prop="sort">
              <el-input
                placeholder="序号值越大，越靠前"
                v-model="ruleForm.sort"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="选择图片" prop="selectedPicList">
              <el-checkbox-group v-model="ruleForm.selectedPicList">
                <el-checkbox
                  class="pic_checkbox"
                  v-for="(item, i) in spuPicList"
                  :key="i"
                  :label="item.url"
                  border
                >
                  <img width="30px" height="30px" :src="item.url" alt="" />
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确认新增SKU</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentSpu: {}, // 保存当前Spu
      addDialogVisible: false, // 新增SKU弹窗是否显示
      attrList: [], // 描述当前模板包含的所有属性列表
      selectedAttrList: [], // 描述用户选中的sku属性列表
      spuPicList: [], // 描述当前SPU包含的图片列表
      currentPage: 1, // 表示当前页码
      pageSize: 5, // 表示每页多少条
      total: 1, // 表示总条目数

      ruleForm: {
        // 描述选中的图片列表
        selectedPicList: [],
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        stock: [{ required: true, message: "请选择库存数量", trigger: "blur" }],
        stockThreshold: [
          { required: true, message: "请输入库存警戒阈值", trigger: "blur" },
        ],
      },
      tableData: [],
    };
  },

  /**
   * 页面挂在完毕后执行
   */
  mounted() {
    let spuId = this.$route.params.id;
    this.currentSpu.id = spuId;
    console.log(spuId);
    // 通过spuId查询详情
    this.$api.spuApi.queryById({ id: spuId }).then((res) => {
      console.log("查询spu详情", res);
      if (res.data.state == 200) {
        this.currentSpu = res.data.data;
        // 根据albumId查询SPU图片列表，供新增SKU时选择
        this.queryPicsByAlbumId(this.currentSpu.albumId);
        // 根据模板ID查询销售属性列表
        this.querySalesByTemplateId(this.currentSpu.attributeTemplateId);
      } else {
        this.$alert(res.data.message, "提示");
      }
    });

    // 根据spuID 查询SKU列表
    this.querySkuList();
  },

  methods: {

    /**
     * 同步SPU库存
     */
    handleStockSynchronise(){
      let id = this.currentSpu.id
      this.$api.spuApi.synchroniseStock({id}).then(res=>{
        console.log("同步SPU库存", res)
        if(res.data.state == 200){
          this.$alert("同步SPU库存完成", '提示')
        }else{
          this.$alert(res.data.message, '提示')
        }
      })
    },

    /**
     * 同步SPU价格
     */
    handlePriceSynchronise(){
      let id = this.currentSpu.id
      this.$api.spuApi.synchronisePrice({id}).then(res=>{
        console.log("同步SPU价格", res)
        if(res.data.state == 200){
          this.$alert("同步SPU价格完成", '提示')
        }else{
          this.$alert(res.data.message, '提示')
        }
      })
    },

    /**
     * 根据spuId查询sku列表
     */
    querySkuList() {
      let spuId = this.currentSpu.id;
      let page = this.currentPage;
      let pageSize = this.pageSize;
      this.$api.skuApi.queryBySpuId({ page, pageSize, spuId }).then((res) => {
        console.log("根据spuID查询sku列表", res);
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
      });
    },

    /**
     * 显示添加sku弹出框
     */
    showAddSkuDialog() {
      // 初始化多选列表，否则checkbox无法完成数据绑定
      this.attrList.forEach((item) => {
        if (item.inputType == 2) {
          this.$set(this.selectedAttrList, item.name, []);
        }
      });
      this.addDialogVisible = true;
    },

    /**
     * 通过相册ID查询图片列表
     */
    queryPicsByAlbumId(albumId) {
      this.$api.picturesApi.queryByAlbumId({ albumId }).then((res) => {
        console.log("根据AlbumId查询图片列表", res);
        if (res.data.state == 200) {
          this.spuPicList = res.data.data.list;
        } else {
          this.$alert(res.data.message, "提示");
        }
      });
    },

    /**
     * 通过模板ID查询销售属性列表
     */
    querySalesByTemplateId(templateId) {
      let page = 1;
      let pageSize = 1000;
      this.$api.attributeApi
        .querySalesByTemplateId({ templateId, page, pageSize })
        .then((res) => {
          console.log("根据模板ID查询属性列表", res);
          this.attrList = res.data.data.list;
        });
    },

    /**
     * 提交表单
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 补上参数specifications配置
          // 将specifications转成specificationArray数组格式
          // specifications:  {"附加商品":["配套彩笔"],"版本":"3本装","年龄段":"3~5岁"}
          // specificationArray: [
          //   { "attributeId":x,
          //     "attributeName":"附加商品",
          //     "attributeValue":"配套彩笔"
          //   }, .....]
          let specificationArray = [];
          this.attrList.forEach((item) => {
            specificationArray.push({
              attributeId: item.id,
              attributeName: item.name,
              attributeValue: this.selectedAttrList[item.name].toString(),
            });
          });
          this.ruleForm.specifications = JSON.stringify(specificationArray);
          // 补上参数pictures
          this.ruleForm.pictures = JSON.stringify(
            this.ruleForm.selectedPicList
          );
          // 补上albumId
          this.ruleForm.albumId = this.currentSpu.albumId;
          // 补上spuId
          this.ruleForm.spuId = this.currentSpu.id;
          // 补上templateId
          this.ruleForm.attributeTemplateId =
            this.currentSpu.attributeTemplateId;
          console.log(this.ruleForm);
          // 发送请求，添加sku
          this.$api.skuApi.add(this.ruleForm).then((res) => {
            console.log("添加sku结果", res);
            if (res.data.state == 200) {
              this.addDialogVisible = false;
              this.$message({
                showClose: true,
                message: "恭喜你，新增SKU成功",
                type: "success",
              });
              // 重新加载sku列表
              this.querySkuList();
            } else {
              this.$alert(res.data.message, "提示");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     *  处理更新页码后的业务 
     */
    handleCurrentChange(val) {
      console.log(`即将加载选中页: 第${val}页`);
      this.currentPage = val;
      this.querySkuList();
    },

    /**
     *  删除SKU 
     */
    deleteSku(id) {
      this.$confirm("确认删除该SKU?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 选择确认，执行删除业务
        this.$api.skuApi.delete({ id: id }).then((res) => {
          console.log("删除Sku操作：", res);
          if (res.data.state == 200) {
            // 删除成功，重新加载Sku列表
            this.querySkuList();
          } else {
            this.$alert(res.data.message, "提示");
          }
        });
      });
    },
  },
};
</script>

<style scoped>
.el-checkbox.is-bordered {
  padding: 5px;
}
.el-checkbox.is-bordered >>> .el-checkbox__input {
  display: none;
}
.el-checkbox.is-bordered >>> .el-checkbox__label {
  padding: 0;
}
.pic_checkbox {
  margin-right: 5px !important;
  margin-left: 0px !important;
}
</style>
